<template>
  <div class="fixed inset-0 bg-gradient-to-b from-blue-400 via-blue-200 to-green-300 flex items-center justify-center">
    <button 
      @click="$router.push('/')" 
      class="absolute top-4 left-4 px-4 py-2 bg-white/20 backdrop-blur-sm rounded-full text-white hover:bg-white/30 transition-all duration-300 flex items-center space-x-2 z-50"
    >
      <span>←</span>
      <span>返回选择</span>
    </button>

    <!-- 游戏状态栏 -->
    <div class="absolute top-4 right-4 flex space-x-4 z-50">
      <div class="stats-card">
        <span class="text-lg text-gray-600">得分</span>
        <span class="text-3xl font-bold text-purple-600 animate-pulse">{{ score }}</span>
      </div>
      <div class="stats-card">
        <span class="text-lg text-gray-600">箭矢</span>
        <span class="text-3xl font-bold text-purple-600 animate-pulse">{{ arrows }}</span>
      </div>
      <div class="stats-card">
        <span class="text-lg text-gray-600">最高分</span>
        <span class="text-3xl font-bold text-purple-600">{{ highScore }}</span>
      </div>
    </div>

    <!-- 游戏场景 -->
    <div class="absolute inset-0 overflow-hidden">
      <!-- 草原背景 -->
      <div class="absolute bottom-0 w-full h-1/3 bg-gradient-to-t from-green-500 to-green-400">
        <!-- 装饰性草 -->
        <div v-for="i in 20" :key="i" 
          class="grass absolute bottom-0"
          :style="{
            left: `${Math.random() * 100}%`,
            height: `${20 + Math.random() * 30}px`,
            animationDelay: `${Math.random() * 2}s`
          }"
        ></div>
      </div>

      <!-- 靶子 -->
      <div 
        class="target-board absolute"
        :style="{
          left: `${targetPosition.x}%`,
          top: '30%',
          transform: 'translate(-50%, -50%)'
        }"
      >
        <div class="ring ring-10"></div>
        <div class="ring ring-9"></div>
        <div class="ring ring-8"></div>
        <div class="ring ring-7"></div>
        <div class="ring ring-6"></div>
        <div class="ring ring-5"></div>
        <div class="ring ring-4"></div>
        <div class="ring ring-3"></div>
        <div class="ring ring-2"></div>
        <div class="ring ring-1"></div>
        
        <!-- 插在靶子上的箭 -->
        <div 
          v-for="hit in hits" 
          :key="hit.id"
          class="arrow-hit"
          :style="{
            left: `${hit.x}px`,
            top: `${hit.y}px`,
            transform: `rotate(${hit.angle}deg)`
          }"
        >
          <div class="arrow-shaft">
            <div class="arrow-head"></div>
            <div class="arrow-fletching"></div>
          </div>
        </div>
      </div>

      <!-- 弓箭手 -->
      <div 
        class="archer absolute bottom-20 transform -translate-x-1/2"
        :style="{ left: `${archerPosition}px` }"
      >
        <div class="relative">
          <!-- 弓 -->
          <div 
            class="bow"
            :class="{ 'is-drawing': isDrawing }"
            :style="{ transform: `rotate(${bowAngle}deg)` }"
          >
            <!-- 弓臂 -->
            <div class="bow-limb bow-limb-top"></div>
            <div class="bow-handle"></div>
            <div class="bow-limb bow-limb-bottom"></div>
            
            <!-- 弓弦 -->
            <div class="bow-string-container">
              <div class="bow-string" :style="{ transform: `scaleY(${isDrawing ? 1.3 : 1})` }">
                <div class="string-nocking-point"></div>
              </div>
            </div>
          </div>
          
          <!-- 拉弓时的箭矢 -->
          <div 
            v-if="isDrawing"
            class="arrow-drawing"
            :style="{ 
              transform: `rotate(${bowAngle}deg) translateX(${drawPower * 60}px)`,
              opacity: drawPower
            }"
          >
            <div class="arrow-shaft">
              <div class="arrow-head"></div>
              <div class="arrow-fletching">
                <div class="fletching fletching-1"></div>
                <div class="fletching fletching-2"></div>
                <div class="fletching fletching-3"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 瞄准辅助线 -->
      <svg 
        v-if="isDrawing"
        class="aim-line absolute pointer-events-none"
        :style="{
          left: `${archerPosition}px`,
          bottom: '80px',
          transform: `rotate(${bowAngle}deg)`,
          transformOrigin: 'bottom'
        }"
      >
        <line 
          x1="0" 
          y1="0" 
          x2="0" 
          :y2="-drawPower * 200" 
          stroke="rgba(255,255,255,0.5)" 
          stroke-dasharray="5,5"
        />
      </svg>
    </div>

    <!-- 游戏控制区域 -->
    <div 
      class="absolute inset-0"
      @mousemove="handleMouseMove"
      @mousedown="startDrawing"
      @mouseup="releaseArrow"
      @mouseleave="cancelDrawing"
    ></div>

    <!-- 得分提示 -->
    <div 
      v-for="popup in scorePopups"
      :key="popup.id"
      class="score-popup absolute pointer-events-none"
      :style="popup.style"
      :class="popup.score >= 8 ? 'text-yellow-400' : 'text-white'"
    >
      +{{ popup.score }}
    </div>

    <!-- 开始游戏提示 -->
    <div 
      v-if="!gameActive && !gameOver" 
      class="absolute inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm"
    >
      <div class="text-center">
        <h1 class="text-5xl font-bold text-white mb-8 animate-bounce">草原射箭</h1>
        <div class="text-xl text-white space-y-4 mb-8">
          <p>按住鼠标左键拉弓</p>
          <p>拉弓时间越长，射程越远</p>
          <p>瞄准靶心，环数越小分数越高</p>
          <p>10环: 10分 | 9环: 9分 | ... | 1环: 1分</p>
        </div>
        <button
          @click="startNewGame"
          class="bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-110"
        >
          开始游戏
        </button>
      </div>
    </div>

    <!-- 游戏结束界面 -->
    <div v-if="gameOver" class="absolute inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div class="bg-white rounded-3xl p-8 text-center transform animate-bounce-slow">
        <h2 class="text-3xl font-bold text-green-600 mb-6 animate-wiggle">
          🎯 游戏结束! 🎯
        </h2>
        <p class="text-xl text-gray-700 mb-2">最终得分: {{ score }}</p>
        <p class="text-xl text-gray-700 mb-2">命中率: {{ hitRate }}%</p>
        <p class="text-lg text-purple-600 mb-8">历史最高分: {{ highScore }}</p>
        <button
          @click="startNewGame"
          class="bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-110"
        >
          再玩一次
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

interface Target {
  id: number;
  x: number;
  y: number;
  isGolden: boolean;
  speed: number;
  direction: number;
}

interface Arrow {
  id: number;
  startX: number;
  startY: number;
  endX: number;
  endY: number;
  timestamp: number;
}

interface Hit {
  id: number;
  x: number;
  y: number;
  angle: number;
  score: number;
}

interface ScorePopup {
  id: number;
  score: number;
  style: {
    left: string;
    top: string;
  };
}

const score = ref(0);
const arrows = ref(10);
const highScore = ref(0);
const gameActive = ref(false);
const gameOver = ref(false);
const combo = ref(0);
const maxCombo = ref(0);
const targets = ref<Target[]>([]);
const activeArrows = ref<Arrow[]>([]);
const mousePosition = ref({ x: 0, y: 0 });
const targetIdCounter = ref(0);
const arrowIdCounter = ref(0);

const archerPosition = ref(window.innerWidth / 2);
const bowAngle = ref(0);
const isDrawing = ref(false);
const drawStartTime = ref(0);
const drawPower = ref(0);
const maxDrawTime = 1500; // 最大拉弓时间（毫秒）

const hits = ref<Hit[]>([]);
const scorePopups = ref<ScorePopup[]>([]);
const targetPosition = ref({ x: 50 });
const hitCount = ref(0);

const hitRate = computed(() => {
  if (hits.value.length === 0) return 0;
  return Math.round((hitCount.value / (10 - arrows.value)) * 100);
});

// 计算箭矢命中位置和得分
const calculateHit = (x: number, y: number) => {
  const targetRect = document.querySelector('.target-board')?.getBoundingClientRect();
  if (!targetRect) return null;

  const targetCenterX = targetRect.left + targetRect.width / 2;
  const targetCenterY = targetRect.top + targetRect.height / 2;
  
  const distance = Math.sqrt(
    Math.pow(x - targetCenterX, 2) + 
    Math.pow(y - targetCenterY, 2)
  );

  const maxRadius = targetRect.width / 2;
  const ringWidth = maxRadius / 10;
  
  // 计算环数（10环到1环）
  const ring = 11 - Math.ceil(distance / ringWidth);
  
  if (ring > 0) {
    hitCount.value++;
    return {
      x: x - targetRect.left,
      y: y - targetRect.top,
      score: ring
    };
  }
  
  return null;
};

const handleMouseMove = (e: MouseEvent) => {
  if (!gameActive.value) return;

  // 更新弓箭手位置
  archerPosition.value = e.clientX;

  // 计算瞄准角度（-45到45度之间）
  const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  const centerX = archerPosition.value;
  const centerY = rect.bottom - 60;
  const angleRad = Math.atan2(centerY - e.clientY, e.clientX - centerX);
  bowAngle.value = Math.max(-45, Math.min(45, angleRad * (180 / Math.PI)));
};

const startDrawing = () => {
  if (!gameActive.value || arrows.value <= 0) return;
  isDrawing.value = true;
  drawStartTime.value = Date.now();
  
  // 开始蓄力动画
  const animate = () => {
    if (!isDrawing.value) return;
    const elapsed = Date.now() - drawStartTime.value;
    drawPower.value = Math.min(1, elapsed / maxDrawTime);
    requestAnimationFrame(animate);
  };
  requestAnimationFrame(animate);
};

const releaseArrow = (e: MouseEvent) => {
  if (!isDrawing.value || !gameActive.value || arrows.value <= 0) return;
  
  const power = drawPower.value;
  const angle = bowAngle.value;
  
  // 计算箭矢落点
  const hit = calculateHit(e.clientX, e.clientY);
  
  if (hit) {
    // 添加命记录
    hits.value.push({
      id: arrowIdCounter.value++,
      x: hit.x,
      y: hit.y,
      angle: angle,
      score: hit.score
    });
    
    // 添加得分动画
    scorePopups.value.push({
      id: arrowIdCounter.value,
      score: hit.score,
      style: {
        left: `${e.clientX}px`,
        top: `${e.clientY}px`
      }
    });
    
    // 更新分数
    score.value += hit.score;
    
    // 3秒后移除得分动画
    setTimeout(() => {
      scorePopups.value = scorePopups.value.filter(p => p.id !== arrowIdCounter.value);
    }, 3000);
  }
  
  arrows.value--;
  
  // 重置拉弓状态
  isDrawing.value = false;
  drawPower.value = 0;
  
  if (arrows.value === 0) {
    endGame();
  }
};

const cancelDrawing = () => {
  isDrawing.value = false;
  drawPower.value = 0;
};

const getArrowStyle = (arrow: any) => {
  const flightTime = 1000; // 箭矢飞行时间（毫秒）
  const elapsed = Date.now() - arrow.timestamp;
  const progress = Math.min(elapsed / flightTime, 1);
  
  // 计算抛物线轨迹
  const x = arrow.startX + (arrow.power * 500 * Math.cos(arrow.angle) * progress);
  const y = arrow.startY - (
    arrow.power * 500 * Math.sin(arrow.angle) * progress -
    (0.5 * 9.8 * Math.pow(progress * flightTime / 1000, 2))
  );
  
  return {
    left: `${x}px`,
    top: `${y}px`,
    transform: `rotate(${arrow.angle * (180 / Math.PI)}deg)`,
    opacity: progress < 1 ? 1 : 0
  };
};

const getTargetStyle = (target: Target) => ({
  left: `${target.x}%`,
  top: `${target.y}%`,
  transform: 'translate(-50%, -50%)',
  fontSize: target.isGolden ? '3rem' : '2rem'
});

const createTarget = () => {
  const isGolden = Math.random() < 0.2; // 20% 概率生成金色目标
  targets.value.push({
    id: targetIdCounter.value++,
    x: Math.random() * 80 + 10,
    y: Math.random() * 80 + 10,
    isGolden,
    speed: isGolden ? 2 : 1,
    direction: Math.random() * Math.PI * 2
  });
};

const updateTargets = () => {
  targets.value.forEach(target => {
    target.x += Math.cos(target.direction) * target.speed;
    target.y += Math.sin(target.direction) * target.speed;

    // 碰到边界时反弹
    if (target.x < 10 || target.x > 90) {
      target.direction = Math.PI - target.direction;
    }
    if (target.y < 10 || target.y > 90) {
      target.direction = -target.direction;
    }
  });
};

let gameLoop: number;

const startNewGame = () => {
  score.value = 0;
  arrows.value = 10;
  gameActive.value = true;
  gameOver.value = false;
  hits.value = [];
  scorePopups.value = [];
  hitCount.value = 0;
  arrowIdCounter.value = 0;
};

const endGame = () => {
  gameActive.value = false;
  gameOver.value = true;
  if (score.value > highScore.value) {
    highScore.value = score.value;
  }
  clearInterval(gameLoop);
};

onUnmounted(() => {
  clearInterval(gameLoop);
});
</script>

<style scoped>
.stats-card {
  @apply flex flex-col items-center p-4 bg-white/90 rounded-xl shadow-md backdrop-blur-sm;
}

.crosshair {
  @apply absolute w-6 h-6 pointer-events-none;
  transform: translate(-50%, -50%);
  background: 
    linear-gradient(to right, transparent 48%, red 48%, red 52%, transparent 52%),
    linear-gradient(to bottom, transparent 48%, red 48%, red 52%, transparent 52%);
}

.target {
  @apply text-4xl filter drop-shadow-lg;
  transition: all 0.3s ease;
}

.golden-target {
  filter: drop-shadow(0 0 10px gold);
}

.arrow {
  @apply text-2xl pointer-events-none;
  transition: all 0.3s ease;
}

.archer {
  @apply text-4xl z-10;
}

.bow {
  @apply relative;
  width: 20px;
  height: 160px;
  transform-origin: center;
  transition: all 0.3s ease;
}

.bow-limb {
  @apply absolute left-1/2 w-6 rounded-full;
  height: 40%;
  background: linear-gradient(90deg,
    #8B4513 0%,
    #A0522D 50%,
    #8B4513 100%
  );
  transform: translateX(-50%);
  box-shadow: 
    inset -2px 0 4px rgba(0,0,0,0.3),
    2px 0 4px rgba(0,0,0,0.2);
}

.bow-limb-top {
  top: 0;
  transform-origin: bottom;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}

.bow-limb-bottom {
  bottom: 0;
  transform-origin: top;
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
}

.bow-handle {
  @apply absolute left-1/2 w-8 bg-gradient-to-r from-yellow-800 to-yellow-900;
  height: 30%;
  top: 35%;
  transform: translateX(-50%);
  border-radius: 4px;
  box-shadow: 
    inset -2px 0 4px rgba(0,0,0,0.4),
    2px 0 4px rgba(0,0,0,0.3);
}

.bow-string-container {
  @apply absolute inset-0;
  pointer-events: none;
}

.bow-string {
  @apply absolute left-1/2 h-full w-0.5;
  background: rgba(255, 255, 255, 0.8);
  transform-origin: center;
  transition: transform 0.3s ease;
  box-shadow: 0 0 2px rgba(255, 255, 255, 0.5);
}

.string-nocking-point {
  @apply absolute left-1/2 w-2 h-2 bg-red-500 rounded-full;
  top: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 4px rgba(255, 0, 0, 0.5);
}

.is-drawing .bow-limb-top {
  transform: translateX(-50%) rotate(-20deg);
}

.is-drawing .bow-limb-bottom {
  transform: translateX(-50%) rotate(20deg);
}

.arrow-shaft {
  @apply relative;
  width: 120px;
  height: 3px;
  background: linear-gradient(to right,
    #D2B48C,
    #DEB887 50%,
    #D2B48C
  );
  border-radius: 1.5px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.2);
}

.arrow-head {
  @apply absolute right-0 transform -translate-y-1/2;
  top: 50%;
  width: 16px;
  height: 8px;
  background: linear-gradient(90deg,
    #808080 0%,
    #A8A8A8 50%,
    #C0C0C0 100%
  );
  clip-path: polygon(0 50%, 30% 0, 100% 50%, 30% 100%);
  box-shadow: 2px 0 4px rgba(0,0,0,0.3);
}

.arrow-fletching {
  @apply absolute left-0 top-1/2;
  transform: translateY(-50%);
}

.fletching {
  @apply absolute w-12 h-1.5;
  background: linear-gradient(to right,
    #FF0000,
    rgba(255, 0, 0, 0.5)
  );
  transform-origin: left;
}

.fletching-1 {
  transform: rotate(-30deg) translateY(-4px);
}

.fletching-2 {
  transform: rotate(30deg) translateY(4px);
}

.fletching-3 {
  width: 8px;
  left: -4px;
  background: #FF0000;
}

.arrow-drawing {
  @apply absolute left-1/2 top-1/2;
  transform-origin: left;
}

/* 飞行箭矢效果 */
.flying-arrow .arrow-shaft {
  filter: drop-shadow(0 0 3px rgba(255,255,255,0.6));
}

.flying-arrow .arrow-head {
  filter: drop-shadow(0 0 2px rgba(192,192,192,0.8));
}

.flying-arrow .fletching {
  animation: flutter 0.2s linear infinite;
}

@keyframes flutter {
  0%, 100% { transform: rotate(var(--base-rotation)); }
  50% { transform: rotate(calc(var(--base-rotation) + 5deg)); }
}

/* 添加命中效果 */
.arrow-hit {
  animation: hit-shake 0.3s ease-out;
}

@keyframes hit-shake {
  0% { transform: scale(1.2) rotate(var(--angle)); }
  100% { transform: scale(1) rotate(var(--angle)); }
}

/* 力度指示器美化 */
.power-meter {
  @apply absolute left-1/2 -top-8;
  width: 100px;
  height: 4px;
  background: linear-gradient(to right,
    #22C55E,
    #FBBF24,
    #EF4444
  );
  border-radius: 2px;
  transform: translateX(-50%);
  overflow: hidden;
}

.power-meter::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255,255,255,0.4),
    transparent
  );
  animation: power-shine 1s linear infinite;
}

@keyframes power-shine {
  from { transform: translateX(-100%); }
  to { transform: translateX(100%); }
}

.aim-line {
  width: 2px;
  height: 200px;
}

.target-board {
  width: 200px;
  height: 200px;
  position: relative;
}

.ring {
  position: absolute;
  border-radius: 50%;
  width: 100%;
  height: 100%;
  transform: scale(var(--scale));
}

.ring-10 { background: white; --scale: 1; }
.ring-9 { background: white; --scale: 0.9; }
.ring-8 { background: red; --scale: 0.8; }
.ring-7 { background: red; --scale: 0.7; }
.ring-6 { background: blue; --scale: 0.6; }
.ring-5 { background: blue; --scale: 0.5; }
.ring-4 { background: black; --scale: 0.4; }
.ring-3 { background: black; --scale: 0.3; }
.ring-2 { background: yellow; --scale: 0.2; }
.ring-1 { background: yellow; --scale: 0.1; }

.grass {
  width: 4px;
  background: linear-gradient(to top, #2d5a27, #4a9c44);
  transform-origin: bottom;
  animation: sway 2s ease-in-out infinite alternate;
}

@keyframes sway {
  from { transform: rotate(-10deg); }
  to { transform: rotate(10deg); }
}

.score-popup {
  font-size: 24px;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  animation: float-up 2s ease-out forwards;
}

@keyframes float-up {
  0% {
    transform: translateY(0);
    opacity: 1;
  }
  100% {
    transform: translateY(-50px);
    opacity: 0;
  }
}

.arrow-hit {
  position: absolute;
  transform-origin: center;
}

/* 其他动画样式保持不变 */
</style>
